package com.example.gomoku;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

public class CircularImageView extends AppCompatImageView {
    private Paint paint;
    private int radius;
    private BitmapShader shader;
    public CircularImageView(@NonNull Context context) {
        super( context );
        init();
    }

    public CircularImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super( context, attrs, defStyleAttr );
        init();
    }

    public CircularImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super( context, attrs );
        init();
    }
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            int viewWidth = getWidth();
            int viewHeight = getHeight();
            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            float scale = Math.max((float) viewWidth / bitmapWidth, (float) viewHeight / bitmapHeight);
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmapWidth * scale), (int) (bitmapHeight * scale), true);
            shader = new BitmapShader(scaledBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);
            radius = Math.min(viewWidth / 2, viewHeight / 2);
            canvas.drawCircle(viewWidth / 2, viewHeight / 2, radius, paint);
        } else {
            // Fallback to default drawing if not a BitmapDrawable
            super.onDraw(canvas);
        }
    }
}
